<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\Admin;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserService extends BaseService
{
    protected $modelClass = User::class;

    /**
     * 指定guard
     */
    private function guard()
    {
        return Auth::guard('admin');
    }

    /**
     * 生成token
     * @param $credentials
     * @return mixed
     */
    public function attempt($credentials)
    {
        return $this->guard()->attempt($credentials);
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function member()
    {
        $member = $this->guard()->user();

        return $member;
    }

    /**
     * 刷新token
     * @return mixed
     */
    public function refresh()
    {
        return $this->guard()->refresh();
    }

    /**
     * 退出
     */
    public function logout()
    {
        return $this->guard()->logout();
    }

    /**
     * 测试方法
     */
    public function index()
    {
        echo 'index';
    }

    /**
     * 注册
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function register($postData)
    {
        $postData['uuid'] = uuid();
        $postData['salt'] = str_random(6);
        $obj = $this->saveData($postData);

        return $obj->uuid;
    }

    /**
     * 详情
     */
    public function detail($id)
    {
        try {
            return $this->find($id, 'admin_id')->first();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 添加
     * @param $postData
     * @return mixed
     * @throws \Throwable
     */
    public function add($postData)
    {
        try {
            if (!$postData['password']) {
                $postData['password'] = '123456';
            }

            return \DB::transaction(function() use($postData) {
                $obj = $this->saveData($postData);

                return $obj;
            });
        } catch (\Exception $e) {
            throw new \Exception('添加失败！');
        }
    }

    /**
     * 编辑
     */
    public function edit($id, $postData)
    {
        try {
            return \DB::transaction(function() use($id, $postData) {
                $user = $this->model
                    ->where(['admin_id'=>$id])
                    ->first();
                if (!$user or !Hash::check(encode_pwd($postData['oldPassword']), $user->password)) {
                    throw new \Exception('原密码错误！');
                }

                if ($postData['oldPassword']==$postData['password']) {
                    throw new \Exception('新旧密码不能相同！');
                }

                $user->update(filter_null($postData));

                return $user;
            });
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 删除员工
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function remove($id)
    {
        try {
            if ($id == 1) {
                throw new \Exception('禁止删除root');
            }

            return $this->removeByField($id, 'admin_id');
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function resetPwd($id)
    {
        try {
            return $this->find($id, 'admin_id')->first()->update(['password' => '123456']);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * @param array $search
     * @param int $per_page
     * @return array
     * @throws \Exception
     */
    public function getList($search=[], $per_page=20)
    {
        $res = $this->model;

        if (!empty($search['user_type'])) {
            $res = $res->where('user_type', $search['user_type']);
        }

        if (!empty($search['keywords'])) {
            $res = $res->where(function($query) use($search) {
                $query->where('username', 'like', "%{$search['keywords']}%")
                    ->orWhere('mobile', 'like', "%{$search['keywords']}%")
                    ->orWhere('email', 'like', "%{$search['keywords']}%");
            });
        }

        if (!empty($search['sort'])) {
            if ($search['sort'] == '-id') {
                $res = $res->orderBy('admin_id', 'desc');
            } else {
                $res = $res->orderBy('admin_id', 'asc');
            }
        }

        return $this->get_paginate($res->paginate($per_page, ['*']));
    }
}
